package com.fuxian.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.fuxian.model.Teacher;
import com.fuxian.util.DateUtile;
import com.fuxian.util.ReturnMapUtil;

@Controller
@Scope("prototype")
public class CommonAction extends BaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = -7888198598835071504L;
	private static final Log log = LogFactory.getLog(CommonAction.class);
	private File upload;
	private String uploadContentType; // 上传文件的类型
	private String uploadFileName; // 上传文件名的属性
	// 直接在struts.xml文件中配置的属性
	private String savePath;

	public String getSavePath() {
		return application.getRealPath(savePath);
	}

	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public void checkValidity() {
	}

	public String uploadImg() {
		returnMap = new HashMap<String, Object>();
		
		
		FileOutputStream fos = null;
		FileInputStream fis = null;
		try {
			if (upload != null) {
				String fileName=  getFileName();
				returnMap.put("photo_path", fileName);
				fos = new FileOutputStream(getSavePath() + File.separator+fileName);
				fis = new FileInputStream(getUpload());
				byte[] buffer = new byte[1024];
				int len = 0;
				while ((len = fis.read(buffer)) > 0) {
					fos.write(buffer, 0, len);
				}
				returnMap = ReturnMapUtil.setReturnHeader(returnMap,true, "上传成功！");
			} else {
				log.info("file is null");
				returnMap = ReturnMapUtil.setReturnHeader(returnMap, false, "所上传文件是空的！");
			}
			
			
		} catch (Exception e) {
			returnMap = ReturnMapUtil.setReturnHeader(returnMap, false, "上传失败!");
			e.printStackTrace();
		}
		
		return SUCCESS;
	}

	private String getFileName() {
		return (String) session.get("user_name") + System.currentTimeMillis()
				+ ".jpg" ;
	}
}
